import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.DatagramSocketImpl;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.zip.DataFormatException;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }


    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true) {
            // DatagramPacket 是一个udp的数据包类
            // 有以下几个方法
            // 1. InetAddress getAddress() 获取发送端的主机ip地址，
            // 2. int getPort()  从接受的数据报中获取对应的主机端口
            // 3. byte[] getData()  获取数据报中的数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],40);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength(), StandardCharsets.UTF_8);
            System.out.println("接收到客户端数据: " + request);

            // 处理请求并生成响应
            String resposnse = process(request);
            byte[] responseBytes = resposnse.getBytes(StandardCharsets.UTF_8);
            DatagramPacket responsePacket = new DatagramPacket(
                    responseBytes,
                    responseBytes.length,
                    requestPacket.getSocketAddress()
            );

            socket.send(responsePacket);
            System.out.println("已经发送响应： " + resposnse);
        }
    }

    public String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
